package com.rose.doorto.footbathdoor.controler;

import com.rose.doorto.common.constant.AuthServerConstant;
import com.rose.doorto.footbathdoor.fegin.AliPayRemoteFeginService;
import com.rose.doorto.footbathdoor.mapper.AddressMapper;
import com.rose.doorto.footbathdoor.pojo.*;
import com.rose.doorto.footbathdoor.service.AddressService;
import com.rose.doorto.footbathdoor.service.IProjectService;
import com.rose.doorto.footbathdoor.service.OrderService;
import com.rose.doorto.footbathdoor.service.TeacherService;
import com.rose.doorto.footbathdoor.service.impl.OrderServiceImpl;
import com.rose.doorto.footbathdoor.util.Result;
import com.rose.doorto.footbathdoor.vo.FormVo;
import com.rose.doorto.footbathdoor.vo.OrderCreateVO;
import com.rose.doorto.footbathdoor.vo.OrderSubmitVO;
import com.rose.doorto.footbathdoor.vo.OrderVo;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import static org.apache.ibatis.ognl.DynamicSubscript.all;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lqc
 * @since 2024-07-23
 */
@Controller
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private AddressService addressService;

    @Autowired
    private IProjectService projectService;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private OrderServiceImpl orderServiceImpl;

    @Autowired
    private AliPayRemoteFeginService aliPayRemoteFeginService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 提交订单，创建订单
     *
     */
    @PostMapping("/submit")
    public String submit(OrderSubmitVO submitVO, String serviceTime, HttpSession session,Model model) {
        OrderCreateVO resp = orderService.submit(submitVO,serviceTime,session);
//        return "redirect:http://localhost/orderWeb/topay?orderSn=" + resp.getOrder().getOrderSn();
//        return "http://localhost/orderWeb/topay?orderSn=" + resp.getOrder().getOrderSn();
        Order order = orderService.getOrderByOrderSn(resp.getOrder().getOrderSn());
//        OrderCreateVO resp = order.getOrderDetail(orderSn);
        model.addAttribute("orderCreateVO", order);
        String uuid = UUID.randomUUID().toString();
        /**
         * String var1:
         * String var2:
         * Object var3:
         * MessagePostProcessor var4:
         * CorrelationData var5:
         */
        /**
         * String exchange:
         * String routingKey:
         * Object object:
         * @Nullable CorrelationData correlationData
         */
//        rabbitTemplate.convertAndSend("deadLetterExchangeName","dieLetter",order,new CorrelationData(uuid));
        return "pay.html";
    }


    /**
     * 下单操作
     * @param order
     * @return
     */
    @PostMapping("addOrders")
    public int addOrders(Order order){
        String uuid = UUID.randomUUID().toString();
        order.setOrderSn(uuid);
        int i = orderService.addOrders(order);
        return i;
    }

    @PostMapping("/addOrders2")
    public Result addOrders2(Order order){
        String uuid = UUID.randomUUID().toString();
        order.setOrderSn(uuid);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        order.setCreateTime(date);
        boolean save = orderService.save(order);
        if (save){
            return Result.success(1,200,"创建成功");
        }else {
            return Result.error(500,"创建失败");
        }
    }
    /**
     * 获取我的所有订单
     * @return
     */
    @GetMapping("/findAllByUserId")
    public String findAllByUserId(Model model,HttpSession session){
        User user = (User) session.getAttribute(AuthServerConstant.LOGIN_USER_KEY);
        if (user!=null){
            List<Order> all = orderService.findAllByUserId(user.getId().toString());
        }
        model.addAttribute("allOrder",all);
        System.out.println(all+"获取到的数据==========");
        return "orderIndex.html";
    }

    //TODO  后期完善,先这么写
    /**
     * 根据项目名称模块查询订单列表
     * @param projectName
     * @return
     */
    @GetMapping("/findOrderByLikeProject")
    public String findOrderByLikeProject(@RequestParam("projectName") String projectName,HttpSession session,Model model){
        User attribute = (User) session.getAttribute(AuthServerConstant.LOGIN_USER_KEY);
        String userId = String.valueOf(attribute.getId());
        List<Order> orderList = orderServiceImpl.findOrderByLikeProject(projectName, userId);
        model.addAttribute("orderList",orderList);
        return "/list.html";
    }
    /**
     * 获取指定状态的订单
     * @param status
     * @return
     */
    @GetMapping("/getOrderByStatus")
    public String getOrderByStatus(@RequestParam(name = "status", required = false)  int status,HttpSession session,Model model){
        User attribute = (User) session.getAttribute(AuthServerConstant.LOGIN_USER_KEY);
        List<Order> orderList = orderService.getOrderByStatus(status,attribute.getId());
        model.addAttribute("orderList",orderList);
        return "/list.html";
    }

    /**
     * 获取指定时间范围内的订单记录
     * @param code
     * @return
     */
    @GetMapping("/getOrderByCreatime")
    public String getOrderByCreatime(@RequestParam(name = "code", required = false) int code,Model model,HttpSession session) {
        User attribute = (User) session.getAttribute(AuthServerConstant.LOGIN_USER_KEY);
        List<Order> orderList = orderServiceImpl.getOrderByCreatime(code, attribute.getId());model.addAttribute("orderList",orderList);
        model.addAttribute("orderList",orderList);
        return "/list.html";

    }

    /**
     * 查看订单详情
     * @param orderSn
     * @return
     */
    @GetMapping("/getOrderByOrderSn/{orderSn}")
    @ResponseBody
    public Order getOrderByOrderSn(@PathVariable("orderSn") String orderSn){
        Order order = orderService.getOrderByOrderSn(orderSn);
        return order;
    }

    /**
     * 创建订单
     * @param orderVo
     */
    @ResponseBody
    @RequestMapping("/submitOrder")
    public String submitOrder(@ModelAttribute OrderVo orderVo,HttpSession session,@RequestParam("serviceTime") String serviceTime){
        int submit = orderService.submit(orderVo, session, serviceTime);
        if (submit>=1){
//            return "下单成功";
            return "";
        }else {
            return "下单失败";
        }
    }


    @GetMapping("/topay")
    public String topay(@RequestParam("orderSn") String orderSn,
                        Model model) {
//        OrderCreateVO resp = orderService.getOrderDetail(orderSn);
        Order order = orderService.getOrderByOrderSn(orderSn);
        model.addAttribute("orderCreateVO", order);
        return "pay";
    }


    /**
     * 去支付
     * @param orderSn
     * @return
     */
    @GetMapping("/getToPay/{orderSn}")
    public String getToPay(@PathVariable("orderSn") String orderSn){
        String s = aliPayRemoteFeginService.payOrder(orderSn);
        return s;
    }
    /**
     * 生成订单确认页信息
     * @return
     */
    @PostMapping("/generateOrderPage")
//    public String generateOrderPage(HttpSession session,@ModelAttribute FormVo formBean,@RequestParam("pid") Integer pid,@RequestParam("tid") Integer tid,Model model){
    public String generateOrderPage(HttpSession session,@ModelAttribute FormVo formVo,Model model){
        User attribute = (User) session.getAttribute(AuthServerConstant.LOGIN_USER_KEY);
        OrderVo orderVo = new OrderVo();
        if (attribute != null){
            Integer aid = attribute.getId();   //用户ID
            Address address = addressService.getDefauleAddressByUserId(aid);
            if (address != null){
                //TODO   个人信息部分
                Address defaultAddress = addressMapper.getDefaultAddress(aid); //获取当前登录用户的默认收货地址信息
                String username = defaultAddress.getUsername();  //用户名
                String phone = defaultAddress.getPhone();        //手机号
                String province = defaultAddress.getProvince();  //省份
                String city = defaultAddress.getCity();          //城市
                String countyTown = defaultAddress.getCountyTown(); //县城
                String addressDetails = defaultAddress.getAddressDetails();  //详细地址
                orderVo.setName(username);
                orderVo.setAddress(addressDetails);
                orderVo.setPhone(phone);
                orderVo.setProvince(province);
                orderVo.setCity(city);
                orderVo.setCountyTown(countyTown);
            }
        }
        Long pid = formVo.getPid();
        //TODO 项目信息部分
        Project project = projectService.getById(pid);
        if (project!=null){
            orderVo.setPid(project.getPid());             //项目编号
            orderVo.setProjectName(project.getName());    //项目名称
            orderVo.setImage(project.getImage());         //项目图片
            orderVo.setDuration(project.getDuration());   //服务时长
            orderVo.setProjectPrice(project.getPrice());  //项目金额
        }

        Integer tid = formVo.getTid();
        Teacher teacher = teacherService.getById(tid);
        //TODO 路费应该调用网约车接口,先写死
        orderVo.setTaxiPrice(BigDecimal.valueOf(teacher.getDistance()/2));  //打车费
        orderVo.setTeacherName(teacher.getName());       //技师名字
        orderVo.setTid(teacher.getTid());                //技师编号
        orderVo.setTotalAmount(orderVo.getTaxiPrice().add(project.getPrice()));
        System.out.println("当前技师的数据是000000000000000000000000000000000000000000000000000000000000000000000000000"+teacher);
        System.out.println("orderVo现有数据888888888888888888888888888888888888888888888888888888888888888888888888888"+orderVo);

        List<LocalDateTime> timeIntervals = orderServiceImpl.getTimeIntervals();
        model.addAttribute("intervals",timeIntervals);
        model.addAttribute("orderVo",orderVo);
        return "/orderConfirm.html";
    }

    /**
     * 获取半个小时之后本来8小时的时间 段，每30分钟一段
     *
     * @return
     */
    @GetMapping("/getTimeIntervals")
    public String getTimeIntervals(Model model){
        LocalDateTime nowTime = LocalDateTime.now();  //当前时间
        Duration halfHour = Duration.ofMinutes(30);
        LocalDateTime minus = nowTime.plus(halfHour);//.minus(halfHour);   //半小时后的时间
        LocalDateTime endTime = minus.plusHours(8); // 假设时间区间是8小时
        List<LocalDateTime> intervals = new ArrayList<>();
        while (minus.isBefore(endTime)) {
            intervals.add(minus);
            minus = minus.plus(halfHour);
        }
        model.addAttribute("interval",intervals);
        System.out.println("时间段获取"+intervals);
        return "/orderConfirm.html";
    }



}
